package com.logic.landseaserver.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.logic.landseaserver.service.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.PropertyStatusEnum;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.domain.PropertySign;
import com.logic.landseaserver.domain.PropertySignEstimation;
import com.logic.landseaserver.persistence.read.PropertySignEstimationReadMapper;
import com.logic.landseaserver.persistence.read.PropertySignReadMapper;
import com.logic.landseaserver.persistence.write.PropertySignEstimationWriteMapper;
import com.logic.landseaserver.persistence.write.PropertySignWriteMapper;
import com.logic.landseaserver.service.IProperty;
import com.logic.landseaserver.service.IPropertySign;
import com.logic.landseaserver.ws.dto.PropertySignDTO;
import com.logic.landseaserver.ws.request.PropertySignEstimationReq;
import com.logic.landseaserver.ws.request.PropertySignReq;
import com.logic.landseaserver.ws.response.PropertyDetailResp;
import com.logic.landseaserver.ws.response.SignEstimationListResp;
import com.logic.system.domain.SystemFile;
import com.logic.system.service.ICodeService;
import com.logic.system.service.IFileService;
import com.logic.system.service.IUserService;
import com.logic.system.ws.dto.FileConverter;


@Service
public class PropertySignServiceImpl implements IPropertySign {

    @Autowired
    private IProperty propertyService;
    @Autowired
    private IFileService fileService;
    @Autowired
    private IUserService userService;
    @Autowired
    private PropertySignWriteMapper propertySignWriteMapper;
    @Autowired
    private PropertySignReadMapper propertySignReadMapper;
    @Autowired
    private PropertySignEstimationReadMapper estimationReadMapper;
    @Autowired
    private PropertySignEstimationWriteMapper estimationWriteMapper;
    @Autowired
    private ICodeService codeService;

    @Override
    @Action(name = "上传合同")
    public int insert(Object o) throws BusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        validateForInsert(o);

        PropertySignReq req = (PropertySignReq) o;
        PropertySign sign = PropertySignReq.toPropertyPOJO(req);
        checkTheProperty(sign.getPropertyId());
        sign.setSignVersion(propertySignReadMapper.getMaxVersion(req.getPropertyId()).toString());
        sign.updateCommonInfo(userId);
        propertySignWriteMapper.insertSelective(sign);
        return 0;
    }

    @Override
    public Object get(Integer integer) throws BusinessException {
        return propertySignReadMapper.selectByPrimaryKey(integer);
    }

    @Override
    public void update(Object o) throws BusinessException {

    }

    @Override
    public void delete(String s) throws BusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        if (StringUtils.isEmpty(s)) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IDS_IS_NULL);
        }
        if (s.split(",").length == 0) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_IDS_IS_NULL);
        }

        Map map = new HashMap<>();
        map.put("userId", userId);
        map.put("list", s.split(","));
        propertySignWriteMapper.delete(map);
    }

    @Override
    public List<?> query(QueryUtil queryUtil) {
        return null;
    }

    @Override
    public List<PropertySignDTO> queryList(QueryUtil queryUtil) throws BusinessException {

        List<PropertySignDTO> list = propertySignReadMapper.queryListPage(queryUtil);

        for (int i = 0; list.size() > 0 && i < list.size(); i++) {
            PropertySignDTO dto = list.get(i);
            dto.setContract(FileConverter.fromFileToDTO((SystemFile) this.fileService.get(dto.getContractId())));
        }
        return list;
    }

    @Override
    public Boolean validate(Object o) throws BusinessException {
        return null;
    }

    @Override
    public Boolean validateForInsert(Object o) throws BusinessException {
        PropertySignReq req = (PropertySignReq) o;

        if (req == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_INSERT_OBJ_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getContractName())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_NAME_IS_NULL);
        }
        if (req.getContractId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_CONTRACT_ID_IS_NULL);
        }

        if (req.getPropertyId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_PROPERTY_ID_IS_NULL);
        }

        if (req.getIsFinalSigned() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_CONTRACT_VERSON_IS_NULL);
        }

        return null;
    }

    @Override
    public Boolean validateForUpdate(Object o) throws BusinessException {
        return null;
    }

    @Override
    public Boolean validateForDelete(Object o) throws BusinessException {
        return null;
    }

    @Override
    public Integer signEstimation(PropertySignEstimationReq req) throws BusinessException {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        validateForEstimation(req);
        PropertySignEstimation estimation = PropertySignEstimationReq.toPropertyPOJO(req);
        estimation.updateCommonInfo(userId);
        // User user = (User) userService.get(userId);
        estimationWriteMapper.insertSelective(estimation);
        return null;
    }

    private void checkTheProperty(Integer propertyId) throws BusinessException {
        Object object = propertyService.get(propertyId);

        if (object == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_DELETE_PROPERTY_ID_IS_NULL);
        }
        PropertyDetailResp property = (PropertyDetailResp) object;
        //是否中止
        if (property.getSuspend()) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_HAS_SUSPEND);
        }
        //是否是签订中
        if (!property.getStatus().equals(PropertyStatusEnum.PS4.toString())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_ISNOT_PS4);
        }
        //是否有最终版本
      /*  if (propertySignReadMapper.hasFinalVersion(propertyId) != null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_CONTRACT_VERSON_HAS_FINAL);
        }*/

    }

    @Override
    public List<SignEstimationListResp> signEstimationPage(QueryUtil util) throws BusinessException {
        List<SignEstimationListResp> list = estimationReadMapper.signEstimationPage(util);

        for (int i = 0; list.size() > 0 && i < list.size(); i++) {
            SignEstimationListResp dto = list.get(i);
            dto.setFile(FileConverter.fromFileToDTO((SystemFile) this.fileService.get(dto.getAttachmentId())));
        }
        return list;
    }

    public Boolean validateForEstimation(Object o) throws BusinessException {
        PropertySignEstimationReq req = (PropertySignEstimationReq) o;
        if (req.getPropertySignId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_ID_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getEstimationResultCode())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_RESULT_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getEstimateName())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_ESTIMATION_NAME_IS_NULL);
        }
        if (StringUtils.isEmpty(req.getEstimateRole())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.PROPERTY_SIGN_ESTIMATION_ROLE_IS_NULL);
        }
        return null;
    }
}
